package com.steven.sync;

import java.util.concurrent.Phaser;

/**
 * 阶段执行，遗传算法
 * 举例：水中的物质，在第一阶段杂志过不去，第二阶段微生物过不去，，，，，到最后只剩下纯净水了
 */
public class Phaser_test {



    static class MarriagePhaser extends Phaser{
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase){
                case 0:
                    System.out.println("所有人到齐"+registeredParties);
                    return false;
                case 1:
                    System.out.println("所有人吃完"+registeredParties);
                    return false;
                case 2:
                    System.out.println("所有人离开"+registeredParties);
                    return false;
                case 3:
                    System.out.println("新娘新郎啪啪"+registeredParties);
                    return true;
                default:
                    return true;
            }
        }
    }

  static   MarriagePhaser phaser = new MarriagePhaser();


    static  class  Person extends Thread{
        String name;
        public Person(String name){
            this.name = name;
        }
        public void  arrive() throws InterruptedException {
            Thread.sleep(1000);
            System.out.println(name+"到达现场");
            phaser.arriveAndAwaitAdvance();
        }
        public void  eat() throws InterruptedException {
            Thread.sleep(1000);
            System.out.println(name+"吃完饭");
            phaser.arriveAndAwaitAdvance();
        }

        public void  leave() throws InterruptedException {
            Thread.sleep(1000);
            System.out.println(name+"走了");
            phaser.arriveAndAwaitAdvance();
        }

        public void  papa() throws InterruptedException {

            if("新娘".equals(name) || "新郎".equals(name)){
                Thread.sleep(1000);
                System.out.println(name+"啪啪");
                phaser.arriveAndAwaitAdvance();
            }else {
                System.out.println(name+"撤退");
                //撤退 注销
                phaser.arriveAndDeregister();
            }

        }

        @Override
        public void run() {
            try {
                arrive();
                eat();
                leave();
                papa();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }



    public static void main(String[] args) {
        phaser.bulkRegister(7);
        for (int i = 0; i < 5; i++) {
            new Thread(new Person("person"+i)).start();
        }
        new Thread(new Person("新娘")).start();
        new Thread(new Person("新郎")).start();

    }



}
